/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { message } from 'antd';
import dayjs from 'dayjs';
import _ from 'lodash';
import { Utils } from 'lfun-bg-comp';

const stringIsArray = (str: string): boolean => {
  const regex = /^\[[\s\S]*\]$/;
  return regex.test(str);
};

export const findLabelDeep = (items: any[], v: string, key?: string, valKey?: string, childKey?: string): string => {
  key = key || 'label';
  valKey = valKey || 'value';
  childKey = childKey || 'children';
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    if (item[valKey] === v) {
      return item[key];
    }
    if (item.children) {
      const res = findLabelDeep(item[childKey], v, key, valKey, childKey);
      if (res) {
        return res;
      }
    }
  }
  return '';
};

const findDeep = (items: any[], v: string, valKey?: string, childKey?: string): string => {
  valKey = valKey || 'value';
  childKey = childKey || 'children';
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    if (item[valKey] === v) {
      return item;
    }
    if (item.children) {
      const res = findDeep(item[childKey], v, valKey, childKey);
      if (res) {
        return res;
      }
    }
  }
  return '';
};

const findLabelsDeep = (items: any, text: any): string => {
  if (text) {
    text = _.isArray(text) ? text : text.split(',');
    const arr: any[] = text.map(v => findLabelDeep(items, String(v)));
    return arr.join('-');
  }
  return '';
};

const flattenObject = (obj, prefix = '') => {
  return Object.keys(obj).reduce((acc, key) => {
    const pre = prefix.length ? `${prefix}.` : '';
    if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {
      Object.assign(acc, flattenObject(obj[key], pre + key));
    } else {
      acc[pre + key] = obj[key];
    }
    return acc;
  }, {});
};

const unflattenObject = (obj: any): any => {
  const result = {};
  for (const key in obj) {
    const keys = key.split('.');
    keys.reduce((acc, cur, index) => {
      if (index === keys.length - 1) {
        acc[cur] = obj[key];
      } else {
        acc[cur] = acc[cur] || {};
      }
      return acc[cur];
    }, result);
  }
  return result;
};

// 定义一个自定义的 filterOption 函数，用于高亮搜索关键词
const filterOption = (input, option) => {
  // 此处假设 keyword 是高亮关键词
  const keyword = input.trim().toLowerCase();
  const optionLabel = (option.props.children || option.props.label).toLowerCase();

  // 高亮处理，这里简单用 `<b>` 标签包裹关键字
  // 实际场景可能需要使用专门的高亮组件或样式类
  const highlightedLabel = optionLabel.replace(new RegExp(keyword), `<b>${keyword}</b>`);
  return highlightedLabel.indexOf(keyword) >= 0;
};
const loadingParams: any = {
  key: 'loading',
  type: 'loading',
  content: 'Loading...',
};
const loadingSuccessParams: any = {
  key: 'loading',
  type: 'success',
  content: '加载成功!',
  duration: 2,
};
const loadingErrorParams: any = {
  key: 'loading',
  type: 'error',
  content: '加载失败!',
  duration: 2,
};
const showLoading = () => {
  message.open(loadingParams);
};
const hideLoaing = (success: boolean) => {
  message.open(success ? loadingSuccessParams : loadingErrorParams);
};

/** 格式化时间 */
const formatTime = (time: string, format?: string) => {
  format = format || 'YYYY-MM-DD';
  if (!time) {
    return undefined;
  }

  return dayjs(time).format(format);
};
//let authJson;
// const getAuthInfo = (name: string) => {
//   try {
//     if (!authJson) {
//       const jwt = localStorage.getItem('x-mg-token');
//       const [payload] = jwt.split('.');
//       authJson = JSON.parse(Buffer.from(payload, 'base64').toString('utf-8'));
//     }
//     return authJson[name];
//   } catch (error) {
//     return '';
//   }
// };

const getUserName = () => {
  const userInfo = Utils.getProps('user_nickname');
  return userInfo;
};

const getUserId = () => {
  const userId = Utils.getProps('account_id'); //getAuthInfo('account_id');
  return userId;
};

// const getFileId = (file_uri: string) => {
//   return sessionStorage.getItem(file_uri) || '';
// };

const filterNull = json => {
  for (const key in json) {
    if (typeof json[key] !== 'boolean') {
      if (!json[key]) delete json[key];
    }
  }
  return json;
};

export const isImage = (fileName: string) => {
  if (typeof fileName === 'string') {
    // 获取文件名的后缀部分
    const fileSuffix = fileName?.substring(fileName?.lastIndexOf('.'), fileName?.lastIndexOf('?'));
    // 检查文件后缀是否在图片格式列表中
    return ['.gif', '.jpeg', '.jpg', '.jpeg', '.png', '.icon'].indexOf(fileSuffix) !== -1;
  }
  return false;
};
const pathRootRegex =
  /^(\/((city|county|school|planning_school)\/)?(\w+\/)?(unit|teacher|student)(\/(kg|k12|vocational|institute|administration))?)/gi;
export const getPathRoot = (path?: string) => {
  const pathname = window.location.pathname;
  if (hasPathRoot(pathname)) {
    const arr = pathname.match(pathRootRegex);
    return arr[arr.length - 1] + (path || '');
  }
  return '';
};

export const getPageForPathRoot = (path?: string) => {
  if (hasPathRoot(path)) {
    const arr = window.location.pathname.match(pathRootRegex);
    return arr[arr.length - 1] + (path || '');
  }
  return '';
};

export const hasPathRoot = (path?: string) => {
  return new RegExp(pathRootRegex).test(path);
};
export const diffPath = (pathname: string, power_url: string) => {
  const realPath = pathname.replace(getPathRoot(), '');
  let jump = realPath === power_url;
  if (!jump && realPath.indexOf(power_url) === 0) {
    if (/^\/(details|change|edit)\/\d+$/g.test(realPath.replace(power_url, ''))) {
      jump = true;
    }
  }
  return jump;
};
export const getPagePath = () => {
  const app = Utils.getProps('app');
  const pagePath = window.location.pathname.replace(getPathRoot(), '');
  let pageMenu;
  app?.menu?.forEach(item => {
    if (diffPath(pagePath, item.power_url)) {
      pageMenu = item;
    } else if (item.children) {
      item.children.forEach(sub => {
        if (diffPath(pagePath, sub.power_url)) {
          pageMenu = sub;
        } else if (sub.children) {
          sub.children.forEach(sub2 => {
            if (diffPath(pagePath, sub2.power_url)) {
              pageMenu = sub2;
            }
          });
        }
      });
    }
  });
  return pageMenu || {};
};

export const buildPageItemTxtByEduType = (txt: string) => {
  if (!window.location.pathname.includes('/kg/')) {
    return txt.replace('园所', '学校');
  }
  return txt;
};

export const getInstitutionCategory = () => {
  if (window.location.pathname.indexOf('/sy') !== -1) {
    return 'institution';
  }
  if (window.location.pathname.indexOf('/xz') !== -1) {
    return 'administration';
  }
  return '';
};

export const getPageKey = () => {
  let pathname = window.location.pathname.replace(getPathRoot(), '');
  const regexp = /\/\d+$/g;
  pathname = pathname.replace(regexp, '');
  pathname = pathname.replace('/', '');
  pathname = pathname.replace(/\//g, '-');
  return pathname;
};

export const set_stoge_pz = (page_size, extendkey?: string) => {
  localStorage.setItem(`${getPageKey()}-page-size-${extendkey || 'idx'}`, page_size);
};

export const get_stoge_pz = (defaultsize?: number, extendkey?: string): number => {
  const page_size = localStorage.getItem(`${getPageKey()}-page-size-${extendkey || 'idx'}`);
  if (/\d+/.test(page_size)) {
    return Number(page_size);
  }
  return defaultsize || 10;
};

// 回显数据字典
export const selectDictLabel = (datas, value) => {
  if (value === undefined) {
    return '';
  }
  const actions = [];
  Object.keys(datas).some(key => {
    if (datas[key].value === `${value}`) {
      actions.push(datas[key].label);
      return true;
    }
    return null;
  });
  if (actions.length === 0) {
    actions.push(value);
  }

  return actions.join('');
};

// 回显数据字典（字符串数组）
export const selectDictLabels = (datas, value, separator = ',') => {
  if (value === undefined || value.length === 0) {
    return '';
  }
  if (Array.isArray(value)) {
    value = value.join(',');
  }
  const actions = [];
  const currentSeparator = undefined === separator ? ',' : separator;
  const temp = value.split(currentSeparator);
  Object.keys(value.split(currentSeparator)).some(val => {
    let match = false;
    Object.keys(datas).some(key => {
      if (datas[key].value === `${temp[val]}`) {
        actions.push(datas[key].label + currentSeparator);
        match = true;
      }
      return null;
    });
    if (!match) {
      actions.push(temp[val] + currentSeparator);
    }
    return null;
  });
  return actions.join('').substring(0, actions.join('').length - 1);
};

export const findText = (items, value) => {
  if (!items) {
    return;
  }

  for (const item of items) {
    // Test current object
    if (item.value === value) {
      // eslint-disable-next-line consistent-return
      return item.label;
    }

    // Test children recursively
    const child = findText(item.children, value);
    if (child) {
      // eslint-disable-next-line consistent-return
      return child;
    }
  }
};

export const getEduType = (code: string) => {
  const edu_code = code.slice(6, 9);
  if ([111, 119].includes(Number(edu_code))) {
    return 'kg';
  }
  if (
    [211, 218, 219, 221, 222, 228, 229, 341, 342, 345, 349, 311, 312, 319, 511, 512, 513, 514, 519].includes(
      Number(edu_code)
    )
  ) {
    return 'k12';
  }

  if (
    [351, 352, 361, 362, 363, 364, 365, 366, 368, 369, 321, 329, 331, 332, 371, 931, 932, 933].includes(
      Number(edu_code)
    )
  ) {
    return 'vocational';
  }
};

export const getUnitType = (paths: Array<string>) => {
  if (/(\d|x){12}/gi.test(paths[1])) {
    return 'school';
  }

  return paths[1];
};

export default {
  stringIsArray,
  findLabelDeep,
  findLabelsDeep,
  unflattenObject,
  flattenObject,
  filterNull,
  filterOption,
  showLoading,
  hideLoaing,
  formatTime,
  getUserId,
  getUserName,
  isImage,
  getPathRoot,
  getPageForPathRoot,
  hasPathRoot,
  getPagePath,
  buildPageItemTxtByEduType,
  findDeep,
  getInstitutionCategory,
  getEduType,
};
